<?php

/*
 * $Id: cmFly.php 14 2011-01-23 07:35:00Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2011-01-23 07:35:00 +0000 (Sun, 23 Jan 2011) $
 * $Revision: 14 $
 */

use cmFly\controller\system;
use cmFly\core;
use cmFly\base;

require(__DIR__ . '/controller/system/context_store.php');
require(__DIR__ . '/controller/exceptions/base.php');
require(__DIR__ . '/controller/exceptions/error.php');

class cmFly extends system\context_store {

    private static $tmp_autoload_handler;
    const VERSION='0.3a';

    /**
     *
     * @param string $app_root
     * @return \cmFly\controller\application
     */
    public static function application($app_root) {
	static::lib_register();
	$obj = new cmFly\controller\application($app_root);
	return $obj;
    }
    
    public static function parse_internal_route($route) {
	$arr=explode('/',$route);
	if(!count($arr)) {
	    throw new cmFly\controller\exceptions\error('Route is empty!');
	}
	return $arr;
    }

    public static function get_dir() {
	return __DIR__;
    }

    protected static function lib_register() {
	if (empty(self::$tmp_autoload_handler)) {
	    self::$tmp_autoload_handler = Array(get_called_class(), 'autoload');
	    spl_autoload_register(self::$tmp_autoload_handler);
	}
    }

    public static function lib_unregister() {
	if (!empty(self::$tmp_autoload_handler)) {
	    spl_autoload_unregister(self::$tmp_autoload_handler);
	    unset(self::$tmp_autoload_handler);
	}
    }

    public static function autoload($file_name) {
	$arr = explode('\\', $file_name);
	if (count($arr) < 2) {
	    return false;
	}
	if (array_shift($arr) == 'cmFly' && $arr[0]!='app') {
	    $path = static::get_dir();
	    if($arr[0]=='vendor' && $arr[1]=='modules') {
		$arr[]=$arr[count($arr)-1];
	    }
	    $lib_path = implode('/', $arr);
	    $path.='/' . $lib_path . '.php';
	    if (is_file($path)) {
		require($path);
		return true;
	    }
	}
	return false;
    }

}